package com.kehao.newcoder;


import javafx.beans.binding.ListBinding;
import org.junit.Test;

import java.util.List;


public class NC50Solution {


    private static class ListNode {
        int val;
        ListNode next = null;
    }


    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode header = new ListNode();
        header.next = head;
        ListNode p = head;
        ListNode pre = header;
        while (p!=null){
            head = p;
            for (int i = 0; i < k-1 && p!=null; i++) {
                p = p.next;
            }
            if(p==null) break;
            ListNode rear = p;
            ListNode rearNext = rear.next;
            ListNode reverseList = reverse(head, rear);
            pre.next = reverseList;
            head.next = rearNext;
            pre = head;
            p = rearNext;
        }
        return header.next;
    }

    private ListNode reverse(ListNode head,ListNode rear) {
        ListNode header = new ListNode();
        rear.next = null;
        ListNode p = head;
        ListNode pNext = p.next;
        while (p!=null){
            p.next = header.next;
            header.next = p;
            p = pNext;
            if(pNext!=null) {
                pNext = pNext.next;
            }
        }
        return header.next;
    }


    @Test
    public void test() {
        int[] arr = {1,2,3,4,5};
        int k = 3;
        ListNode head = generateListNode(arr);
        listOutput(head);
        ListNode result = reverseKGroup(head, k);
        listOutput(result);
    }

    private ListNode generateListNode(int[] arr){
        ListNode header = new ListNode();
        ListNode rear = header;
        for (int i = 0; i < arr.length; i++) {
            ListNode node = new ListNode();
            node.val = arr[i];
            rear.next = node;
            rear = node;
        }
        return header.next;
    }

    private void listOutput(ListNode head){
        System.out.print("[");
        while (head!=null){
            System.out.print(head.val+",");
            head = head.next;
        }
        System.out.println("\b]");
    }
}
